import { Injectable } from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { PrismaService } from 'nestjs-prisma'
import { DomainModel } from '../model'

@Injectable()
export class MetaResourceModelDao {
  get table() {
    return this.prismaService.metaResourceModel
  }

  constructor(private readonly prismaService: PrismaService) {}

  /**
   * 数据列表
   * @param data
   * @returns
   */
  list(data: Prisma.MetaResourceModelWhereInput): Promise<DomainModel.MetaResourceModel[]> {
    return this.table.findMany({
      where: data,
      orderBy: {
        createTime: 'desc',
      },
    })
  }

  /**
   * 批量添加
   * @param data
   * @returns
   */
  batchSave(data: Prisma.MetaResourceModelCreateManyInput | Prisma.MetaResourceModelCreateManyInput[]) {
    return this.table.createMany({
      data: (Array.isArray(data) ? data : [data]).map(item => ({
        relativeType: item.relativeType,
        relativeId: item.relativeId,
        type: item.type,
        dataType: item.dataType,
        name: item.name,
        label: item.label,
      })),
    })
  }

  /**
   * 删除关联数据
   * @param data
   * @returns
   */
  deleteByRelative(data: {
    relativeType: DomainModel.MetaResourceRelativeType
    relativeId: number
    type?: DomainModel.MetaResourceModelType
  }) {
    return this.table.deleteMany({
      where: {
        relativeId: data.relativeId,
        relativeType: data.relativeType,
        type: data.type,
      },
    })
  }
}
